package com.dvhung.projectmvcdemo;

import java.util.ArrayList;

import com.dvhung.adapter.ItemAdapter;
import com.dvhung.common.ActionEvent;
import com.dvhung.constants.Constants;
import com.dvhung.controller.ItemController;
import com.dvhung.model.dto.ItemDTO;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends Activity {
	ListView lv1;
	ItemAdapter adapter;
	ArrayList<Object> arrData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		lv1 = (ListView) findViewById(R.id.lv1);
		arrData = new ArrayList<Object>();
		adapter = new ItemAdapter(this, R.layout.adapter_list, arrData);
		lv1.setAdapter(adapter);
		InitData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void InitData() {
		ActionEvent e = new ActionEvent(MainActivity.this, Constants.GET_ITEM,
				null, null);
		ItemController.getInstance().handleViewEvent(e);
	}

	@SuppressWarnings("unchecked")
	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_ITEM:
			ArrayList<ItemDTO> newArr = (ArrayList<ItemDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;

		default:
			break;
		}
	}

	private class VerySlowTask extends AsyncTask<String, Object, Void> {
		ArrayList<ItemDTO> _newArr;

		public VerySlowTask(ArrayList<ItemDTO> arrData) {
			this._newArr = arrData;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			for (int i = 0; i < _newArr.size(); i++) {
				publishProgress(_newArr.get(i));
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			// TODO Auto-generated method stub
			arrData.add(values[0]);
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			adapter.notifyDataSetChanged();
		}

	}

}
